<template>
<div class="noticeofdelivery">


  <div class="head">
    <h2>发货通知单</h2>
    <div class="btns clearfix">
      <el-button class="bind" v-show="!hasBind" :disabled="!editable" type="primary" @click="bindOrder">绑定订单</el-button>
      <!-- <el-button class="export"  :disabled="hasBind ? (!editable) : true" type="primary" @click="exportMethod">导出</el-button> -->
    </div>

    <div class="select-orders">
      <el-row :gutter="20">
        <el-col :span="10">
          <div>
            <p class="select-orders-line">
              选中的外贸订单
              <el-button v-show="hasBind ? editable : false"  @click="bindOrder" type="text">点击修改</el-button>
            </p>
            <ul>
              <!-- <li v-if="showftc"><a :href="'#/initiatingprocess/businessform?dTab=3&formInstId='+ showftc.id + '&formServiceName=' +  showftc.formServiceName">{{this.data.documentprocess_fdn_bindFContracts[0]}}</a></li> -->
              <li><a href="#">{{documentprocess_fdn_bindFContracts[0]}}</a></li>
            </ul>
          </div>
        </el-col>
        <el-col :span="10" :offset="4" >
          <div>
            <p class="select-orders-line">选中的内贸订单</p>
            <ul>

              <!-- <li v-for="item in this.data.documentprocess_fdn_bindDContracts ">
                <a href="#">{{item}}</a>
              </li>
               -->
              <li>
                <a href="#">{{documentprocess_fdn_bindDContracts[0]}}</a>
              </li>
            </ul>
          </div>
        </el-col>
      </el-row>
    </div>


    <div class="tcf-table">
      <div class="procurement-contract">
        <div class="procurement-contract-inner">
          <span>采购合同: </span>
          <input type="text" @input="handleSimpleInput" :readonly="hasBind ? (!editable) : true" v-model="documentprocess_fdn_contracts" placeholder="请输入内容" />
        </div>
      </div>

      <div class="factory-contact-mode">
        <el-row>
          <el-col :span="24">
            <p>工厂联系方式：</p>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="2"><span>工厂名</span></el-col>
          <el-col :span="22" class="factory">
            <!-- <el-input :readonly="hasBind ? (!editable) : true" v-model="data.documentprocess_fdn_fc_factoryName" placeholder="请输入内容"></el-input> -->

         <el-select v-model="documentprocess_fdn_fc_factoryName" :disabled="hasBind ? (!editable) : true"  filterable @change="selFactory"  placeholder="请选择工厂/可搜索">
           <el-option
              v-for="item in sellOptions"
             :key="item.value"
             :label="item.label"
             :value="item.value">
            </el-option>
          </el-select>
          </el-col>
        </el-row>

        <!-- <el-row v-for="(item, index) in data.documentprocess_fdn_fc_dff_contacts " :key="index"> -->
        <el-row>
          <el-col :span="2"><span>联系人</span></el-col>
          <el-col :span="3">
            <input type="text" :readonly="true" v-model="factoryMesg.name" placeholder="请输入内容">
          </el-col>
          <el-col :span="1"><span>电话</span></el-col>
          <el-col :span="4">
            <input type="text" :readonly="true" v-model="factoryMesg.tel" placeholder="请输入内容">
          </el-col>
          <el-col :span="1"><span>QQ</span></el-col>
          <el-col :span="3">
            <input type="text" :readonly="true" v-model="factoryMesg.qq" placeholder="请输入内容">
          </el-col>
          <el-col :span="1"><span>邮箱</span></el-col>
          <el-col :span="5">
            <input type="text" :readonly="true" v-model="factoryMesg.email" placeholder="请输入内容">
          </el-col>
          <el-col :span="1"><span>微信</span></el-col>
          <el-col :span="3">
            <input type="text" :readonly="true" v-model="factoryMesg.wechat" placeholder="请输入内容">
          </el-col>
          <!-- <el-col :span="3" class="operation" v-if="hasBind ? editable : false">
            <el-button type="text" @click="addContact('fac', index)">添加</el-button>
            <el-button type="text" @click="delContact('fac', index)" >移除</el-button>
          </el-col>
          <el-col :span="3" class="operation" v-else>
            <span>无权限操作</span>
          </el-col> -->
        </el-row>
      </div>
      <div class="factory-contact-mode">
        <el-row>
          <el-col :span="24">
            <p>物流公司联系方式：</p>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="2"><span>物流公司名</span></el-col>
          <el-col :span="22">
            <input type="text" @input="handleSimpleInput"  :readonly="hasBind ? (!editable) : true" v-model="documentprocess_fdn_lcc_logisticName" placeholder="请输入内容" />
          </el-col>
        </el-row>
        <el-row v-for="(item,index) in documentprocess_fdn_lcc_dfl_contacts" :key="index">
          <el-col :span="2"><span>联系人</span></el-col>
          <el-col :span="3">
            <input type="text" @input="handleSimpleInput" :readonly="hasBind ? (!editable) : true" v-model="item.name" placeholder="请输入内容">
          </el-col>
          <el-col :span="1"><span>电话</span></el-col>
          <el-col :span="3">
            <input type="text" @input="handleSimpleInput" :readonly="hasBind ? (!editable) : true" v-model="item.tel" placeholder="请输入内容">
          </el-col>
          <el-col :span="1"><span>QQ</span></el-col>
          <el-col :span="3">
            <input type="text" @input="handleSimpleInput" :readonly="hasBind ? (!editable) : true" v-model="item.qq" placeholder="请输入内容">
          </el-col>
          <el-col :span="1"><span>邮箱</span></el-col>
          <el-col :span="3">
            <input type="text" @input="handleSimpleInput" :readonly="hasBind ? (!editable) : true" v-model="item.email" placeholder="请输入内容">
          </el-col>
          <el-col :span="1"><span>微信</span></el-col>
          <el-col :span="3">
            <input type="text" @input="handleSimpleInput" :readonly="hasBind ? (!editable) : true" v-model="item.wechat" placeholder="请输入内容">
          </el-col>
          <el-col :span="3" class="operation" v-if="hasBind ? editable: false">
            <el-button type="text" @click="addContact('log', index)">添加</el-button>
            <el-button type="text" @click="delContact('log', index)" >移除</el-button>
          </el-col>
          <el-col :span="3" class="operation" v-else>
            <span>无权限操作</span>
          </el-col>
        </el-row>
      </div>

      <el-table :data="documentprocess_deliDetail" border style="width: 100%">

        <el-table-column type="index" label="序号" :index="indexMethod"></el-table-column>
        <el-table-column prop="dd_products" label="产品" width="180">
          <template slot-scope="scope">
               <input type="text" @input="handleTableInput(scope, 'dd_products', $event)" 
               :readonly="hasBind ? (!editable) : true" v-model="scope.row.dd_products" placeholder="请输入内容">
           </template>
        </el-table-column>
        <el-table-column prop="dd_description" label="规格型号">
          <template slot-scope="scope">
               <input type="text" @input="handleTableInput(scope, 'dd_description', $event)" 
              :readonly="hasBind ? (!editable) : true" v-model="scope.row.dd_description" placeholder="请输入内容">
          </template>
        </el-table-column>
        <el-table-column prop="dd_quantity" label="数量">
          <template slot-scope="scope">
               <input type="number" @input="handleTableInput(scope, 'dd_quantity', $event)" 
              :readonly="hasBind ? (!editable) : true" v-model="scope.row.dd_quantity" placeholder="请输入内容">
           </template>
        </el-table-column>
        <el-table-column prop="dd_price" label="单价">
          <template slot-scope="scope">
               <input type="number" @input="handleTableInput(scope, 'dd_price', $event)" 
              :readonly="hasBind ? (!editable) : true" v-model="scope.row.dd_price" placeholder="请输入内容">
           </template>
        </el-table-column>
        <el-table-column prop="dd_lineAmount" label="金额">
          <template slot-scope="scope">
               <input type="number" @input="handleTableInput(scope, 'dd_lineAmount', $event)" 
              :readonly="hasBind ? (!editable) : true" v-model="scope.row.dd_lineAmount" placeholder="请输入内容">
          </template>
        </el-table-column>

        <el-table-column
        v-if="hasBind ? editable: false"
        label="操作"
        width="100">
        <template slot-scope="scope">
          <el-button @click="addNewLine(scope.$index, documentprocess_deliDetail)" type="text" size="small">添加</el-button>
          <el-button @click="removeCurrentLine(scope.$index, documentprocess_deliDetail)" type="text" size="small">移除</el-button>
        </template>
      </el-table-column>
      </el-table>

      <div class="extra-table">
          <el-row class="extra-money">
              <el-col :span="17" ><div>合计TOTAL</div></el-col>
              <el-col :span="7">
                <input type="number" :min="0" v-model="documentprocess_deliDetail_total_amount" @input="handleSimpleInput"/>
              </el-col>
          </el-row>
      </div>

      <div class="factory-contact-mode">
        <el-row>
          <el-col :span="24">
            <p>发货情况说明：</p>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="4"><span>发货时间：</span></el-col>
          <el-col :span="20">
            <el-date-picker format="yyyy 年 MM 月 dd 日" value-format="yyyy-MM-dd" :disabled="hasBind ? (!editable) : true"  @change="selectDate"   v-model="documentprocess_fdn_time" type="date" placeholder="选择日期">
            </el-date-picker>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="4"><span>交易方式：</span></el-col>
          <el-col :span="20">
            <input type="text" @input="handleSimpleInput" :readonly="hasBind ? (!editable) : true"  v-model="documentprocess_fdn_tradeTerm" placeholder="请输入内容" />
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="4"><span>产品海关编码：</span></el-col>
          <el-col :span="20">
            <input type="text" @input="handleSimpleInput" :readonly="hasBind ? (!editable) : true"  v-model="documentprocess_fdn_hscode" placeholder="请输入内容" />
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="4"><span>其他情况说明：</span></el-col>
          <el-col :span="20">
            <input type="text" @input="handleSimpleInput" :readonly="hasBind ? (!editable) : true"  v-model="documentprocess_fdn_other" placeholder="请输入内容" />
          </el-col>
        </el-row>
      </div>

    </div>



    <div class="upload">
      <p class="upload-hint">票据/附件</p>
      <div>
        <div class="upload-btn">
          <input type="file"  v-show="hasBind ? editable : false"  name="file" multiple @change="selectFiles">
          <el-button  :disabled="hasBind ? (!editable) : true" type="primary">选择附件</el-button>
        </div>

        <ul class="upload-files">
          <li @mouseover="handleOver(item)"   @mouseout="handleOut(item)" v-for="(item,index) in attachedFiles" :key="index">
            <span @click="download(item.id, $event)">{{item.name}}</span>
            <span v-if="editable && item.status" class="el-icon-circle-check" style="color:#67c23a;"></span>
            <span v-else-if="editable" class="el-icon-circle-close" @click="changeFiles(index,item)" style="color:red;"></span>
          </li>
        </ul>
      </div>
    </div>

  </div>

  <div class="bind-window">
    <el-dialog title="订单绑定" width="70%" :visible.sync="dialogCtrl.outerVisible">

      <el-form :inline="true">
        <el-form-item label="订单编号">
          <el-input v-model="orderNumber" placeholder="请输入订单编号"></el-input>
        </el-form-item>
        <el-form-item label="外贸合同号">
          <el-input v-model="foreignTradeContractNumber" placeholder="请输入外贸合同号"></el-input>
        </el-form-item>

        <el-form-item label="买家名称">
          <el-input v-model="buyerName" placeholder="请输入买家名称"></el-input>
        </el-form-item>


        <el-form-item>
          <el-date-picker
          v-model="orangeDate"
          type="daterange"
          align="right"
          unlink-panels
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :picker-options="pickerOrange">
        </el-date-picker>
      </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="queryFtc(-1)">查询</el-button>
        </el-form-item>
      </el-form>

      <el-table v-loading="loading" :data="table1Data" style="width: 100%" border stripe>
        <el-table-column prop="table1_orderNumber" label="订单编号" sortable width="240" :sort-method="table1Sort">
          <template slot-scope="scope">
            <span>
              <input type="checkbox" :value="scope.row.table1_id" @click="checkBoxRadio('selForder', $event)" v-model="selectOrder">
              <span>{{scope.row.table1_orderNumber}}</span>
            </span>
          </template>
        </el-table-column>

        <el-table-column prop="table1_ftcNumber" label="外贸合同号" sortable>
        </el-table-column>

        <el-table-column prop="table1_createTime" label="订单生成时间" >
        </el-table-column>

        <el-table-column prop="table1_buyerName" label="买家名称" >
        </el-table-column>



        <el-table-column prop="table1_orderProcess" label="订单流程" >
        </el-table-column>

        <el-table-column prop="table1_orderStatus" label="订单状态" >
        </el-table-column>
      </el-table>


      <div class="pageing">
        <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page.currPage"
        :page-sizes="[20, 30, 50, 100]"
        :page-size="page.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="page.totalSize">
      </el-pagination>

    </div>


      <el-dialog width="50%" title="内贸合同绑定" :visible.sync="dialogCtrl.innerVisible" append-to-body>

        <el-table v-loading="loading" :data="table2Data" style="width: 100%" border>
          <el-table-column prop="table2_dtcNumber" label="内贸合同编号" width="200">
            <template slot-scope="scope">
              <span>
                <input type="checkbox" @click="checkBoxRadio('selDorder', $event)" :value="scope.row.table2_id" v-model="selectOrder2">
                <span>{{scope.row.table2_dtcNumber}}</span>
              </span>
            </template>
          </el-table-column>

          <el-table-column prop="table2_sellerName" label="供方名称">
          </el-table-column>

          <el-table-column prop="table2_contractAmount" label="合同金额">
          </el-table-column>
        </el-table>

        <div slot="footer" class="dialog-footer">
          <el-button type="primary" :disabled="canNotSelect2" @click="bindInnerConfirm">确定</el-button>
          <el-button @click="bindInnerCancel">取 消</el-button>
        </div>
      </el-dialog>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" :disabled="canNotSelect" @click="bindOuterSelect">选择内贸合同</el-button>
        <el-button @click="bindOuterCancel">取 消</el-button>
      </div>

    </el-dialog>
  </div>

</div>
</template>

<script>
import {
  uploadFiles,
  queryBindContracts,
  queryBindDtcContracts,
  queryFtcContract,
  queryFtcContractTable,
  getBusinessMesg
} from '@/server/initiatingprocess';

import {filedownload , deleteFile} from '@/server/customermanagement/index.js'
import {setStore, getStore,removeStore} from '@/assets/js/common.js'
import {toFixed} from '@/util/transform.js'


export default {
  created(){
    const self = this;

    this.factoryMesg = _.cloneDeep(this.documentprocess_fdn_fc_dff_contacts[0]);

    this.keys.forEach(key => {
       this[key] = _.cloneDeep(this.datas[key]);
    });

    getBusinessMesg({type: 2}).then(response => {
      this.allSellers = response.data.datas; 
      //卖家信息 == 工厂信息
      //设置成下拉列表

      this.allSellers.forEach((e, i, a) => {
        this.sellOptions.push({
          value: e.customerName,
          labe: e.customerName
        });
      });
    })
  },
  updated() {

  },
  mounted() {
    let self = this;
    let closeDom = document.querySelectorAll('.bind-window i.el-dialog__close.el-icon-close');
    for (let i = 0; i < closeDom.length; i++) {
      closeDom[i].onclick = function() {
        self.bindInnerCancel();
      };
    }
  },
  methods: {

    emitToParent(){
      let temp = {};
      this.keys.forEach(key => {
        temp[key] = this[key];
      });
      this.$emit("fromND", "documentProcess_fd_notice", _.cloneDeep(temp));
    },

    indexMethod(value) {
      let lines = this.documentprocess_deliDetail.length;
      return value + 1;
    },

    selectDate(){
      this.emitToParent();
    },

    specialInitialProcess() {
      let dom = document.querySelector('.initiatingprocess .routers-ctrl');
      if (dom) {
        dom.style.zIndex = '0';
      }
    },
    bindOrder(){
      this.$set(this.dialogCtrl, "outerVisible",true);

      this.canNotSelect = true;
      this.canNotSelect2 = true;

      this.orderNumber = '';
      this.foreignTradeContractNumber = '';
      this.buyerName = '';

      this.queryFtc(1, 30);
    },

    handleSizeChange(size){
      this.$set(this.page, "pageSize",size);
      //需要重新查询
      this.queryFtc(1, this.page.pageSize);
    },
    handleCurrentChange(currPage){
      this.$set(this.page, "currPage",currPage);
      //需要重新查询
      this.queryFtc(this.page.currPage, this.page.pageSize);
    },
    queryFtc(currPage, pageSize) {

      let startTime, endTime;
      //通过查询来获得外贸合同订单，并修改table1的数据来进行显示
      if (currPage ==  -1){
        currPage = 1;
        this.$set(this.page, "currPage",1);
        pageSize = this.page.pageSize;
      }

      this.table1Data = [];
      this.table2Data = [];
      this.selectOrder = [];
      this.loading = true;

      if (this.orangeDate) {
        startTime = new Date('' + this.orangeDate[0]).getTime();
        endTime = new Date('' + this.orangeDate[1]).getTime();

        queryBindContracts({
          flowId: 1,
          orderCode: this.orderNumber,
          ftcCode: this.foreignTradeContractNumber,
          buyerName: this.buyerName,
          currPage: currPage - 1,
          pageSize: pageSize,
          gt_createTime: startTime,
          lt_createTime: endTime
        }).then((response)=>{

          this.$set(this.page, "totalSize", response.data.totalSize);
          this.queryOrderData = response.data.datas;

          this.loading = false;

          let table1Data = [];
          for (let i = 0; i < this.queryOrderData.length; i++) {

            if (!table1Data[i]) {
              table1Data[i] = {};
            }
            table1Data[i].table1_orderNumber = this.queryOrderData[i].orderCode;
            table1Data[i].table1_ftcNumber = this.queryOrderData[i].ftcCode;
            table1Data[i].table1_buyerName = this.queryOrderData[i].buyerName;
            table1Data[i].table1_id = this.queryOrderData[i].id;

            let date = new Date(this.queryOrderData[i].createTime);
            let m = date.getMonth() + 1;
            m = m < 10 ? '0' + m  : m;
            let d = date.getDate();
            d = d < 10 ? '0' + d  : d;

            table1Data[i].table1_createTime = date.getFullYear() + '-' + m + '-' + d;

            switch(this.queryOrderData[i].formInstStatus){
              case 0:
              case 1:
              table1Data[i].table1_orderStatus = '流转中';
              break;
              case 2:
              table1Data[i].table1_orderStatus = '完结';
              break;
            }

            table1Data[i].table1_orderProcess = this.queryOrderData[i].flowName;
          }
          this.table1Data = table1Data;
        });
      } else {
        queryBindContracts({
          flowId: 1,
          orderCode: this.orderNumber,
          ftcCode: this.foreignTradeContractNumber,
          buyerName: this.buyerName,
          currPage: currPage - 1,
          pageSize: pageSize
        }).then((response)=>{

          this.$set(this.page, "totalSize", response.data.totalSize );
          this.queryOrderData = response.data.datas;
          this.loading = false;

          let table1Data =[];
          for (let i = 0; i < this.queryOrderData.length; i++) {

            if (!table1Data[i]) {
              table1Data[i] = {};
            }
            table1Data[i].table1_orderNumber = this.queryOrderData[i].orderCode;
            table1Data[i].table1_ftcNumber = this.queryOrderData[i].ftcCode;
            table1Data[i].table1_buyerName = this.queryOrderData[i].buyerName;
            table1Data[i].table1_id = this.queryOrderData[i].id;


            let date = new Date(this.queryOrderData[i].createTime);
            let m = date.getMonth() + 1;
            m = m < 10 ? '0' + m  : m;
            let d = date.getDate();
            d = d < 10 ? '0' + d  : d;

            table1Data[i].table1_createTime = date.getFullYear() + '-' + m + '-' + d;

            switch(this.queryOrderData[i].formInstStatus){
              case 0:
              case 1:
              table1Data[i].table1_orderStatus = '流转中';
              break;
              case 2:
              table1Data[i].table1_orderStatus = '完结';
              break;
            }

            table1Data[i].table1_orderProcess = this.queryOrderData[i].flowName;
          }
          this.table1Data = table1Data;
        });
      }


    },
    table1Sort(a, b) {
      let a1 = a.toString().slice(a.length - 5);
      let b1 = b.toString().slice(b.length - 5);
      return parseInt(b) - parseInt(b);
    },
    checkBoxRadio(type, event) {
      let value = event.target.value;

      if (type === 'selForder') {

        if (value === this.selectOrder[0]) {
          this.canNotSelect = true;
        } else {
          this.canNotSelect = false;
        }

        this.selectOrder = [value];

        this.showftc = this.queryOrderData.find((e) => {
          return e.id == this.selectOrder[0]
        });

        this.bindFContracts.splice(0, 1, this.showftc.ftcCode);

      } else if (type === 'selDorder'){
        if (value === this.selectOrder2[0]) {
          this.canNotSelect2 = true;
        } else {
          this.canNotSelect2 = false;
        }

        this.selectOrder2 = [value];

        let currDtc = this.queryOrderData2.find((e) => {
          return e.id == this.selectOrder2[0]
        });

        this.bindDContracts.splice(0, 1, currDtc.bd_no);
      }
    },
    bindOuterSelect() {
      let that = this;
      this.dialogCtrl.innerVisible = true;

      let closeDom = document.querySelectorAll('i.el-dialog__close.el-icon-close');
      for (let i = 0; i < closeDom.length; i++) {
        closeDom[i].onclick = function() {
          that.bindInnerCancel();
        };
      }

      /*
      需要根据当前选中的订单值即 checkedFOrder,来修改 table2Data，用于显示该订单下的内贸订单
      */

      //勾选的外贸
      // this.showftc = this.queryOrderData.find((e)=>{
      //   return e.ftcCode == this.bindFContracts[0]
      // });

      this.buyerName = this.showftc.buyerName;
      this.orderCode = this.showftc.orderCode;

      //绑定的外贸订单的id
      this.bindingFormInstId = this.showftc.id;

      this.loading = true;

      queryBindDtcContracts({
        formInstId: this.showftc.id
      }).then((response)=>{
        this.queryOrderData2 = response.data.datas;
        this.loading = false;

        let table2Data = [];

        for (let i = 0; i < this.queryOrderData2.length; i++) {

          if (!table2Data[i]) {
            table2Data[i] = {};
          }
          table2Data[i].table2_dtcNumber = this.queryOrderData2[i].bd_no;
          table2Data[i].table2_sellerName = this.queryOrderData2[i].bd_seller;
          table2Data[i].table2_contractAmount = this.queryOrderData2[i].bd_table1_totalAmount;
          table2Data[i].table2_id = this.queryOrderData2[i].id;
        }
        this.table2Data = table2Data;
        this.emitToParent();
      });

    },
    bindOuterCancel() {
      this.bindInnerCancel();
    },
    bindInnerConfirm() {
      this.$set(this.dialogCtrl, "outerVisible", false);
      this.$set(this.dialogCtrl, "innerVisible", false);

      if (this.bindDContracts.length === 0) {
        this.bindInnerCancel();
        return;
      }

      this.hasBind = true;
      this.documentprocess_fdn_bindFContracts = _.cloneDeep(this.bindFContracts);
      this.documentprocess_fdn_bindDContracts = _.cloneDeep(this.bindDContracts);

       //勾选的内贸
       // this.showdtcs = this.queryOrderData2.filter((e)=>{
       //    return this.data.documentprocess_fdn_bindDContracts.indexOf(e.bd_no) != -1;
       // });

       this.showdtcs[0] = this.queryOrderData2.find((e)=>{
          return this.documentprocess_fdn_bindDContracts[0] == e.bd_no;
       });

       this.documentprocess_fdn_contracts  = this.showdtcs[0].bd_no;

       //保存一下绑定的内贸合同的formInstId
      //  setStore("formInstId", this.showdtcs[0].formInstId);

       queryFtcContract({
         formInstId: this.showftc.id,
       }).then((response) => {
         let ftc = response.data.datas[0];

         queryFtcContractTable({
           formInstId: this.showftc.id,
           ftcId: ''
         }).then((response) => {

           //得到绑定的外贸合同
           let ftcData = _.extend({}, ftc, {bf_table1:response.data.datas});

           this.bus.$emit('bind-new-ftc', ftcData);

           this.table1Data = [];
           this.table2Data = [];
           this.$set(this.page, "pageSize", 30);
           this.emitToParent();
         });
       });
    },
    bindInnerCancel() {
      this.$set(this.dialogCtrl, "outerVisible", false);
      this.$set(this.dialogCtrl, "innerVisible", false);

      this.bindFContracts = [];
      this.bindDContracts = [];

      this.canNotSelect = true;
      this.canNotSelect2 = true;

      this.selectOrder = [];

      this.page.pageSize = 30;
      this.table1Data = [];
      this.table2Data = [];
    },
    selectFiles(event) {
      //票据附件
      let self = this;

      //直接上传，并且获得后端返回的文件的url,将url保存到 this.data.attachedFiles中
      uploadFiles(event.target.files).then((resArr)=>{
        resArr.forEach(function(res,i){
          self.attachedFiles.push({name: event.target.files[i].name, status: 1, id: res.data.datas[0].id});
        });
        self.emitToParent();
      });
    },
    changeFiles(index,item) {
      deleteFile({'id':item.id}).then((res) => {
        if(res.code != 1 ){
          this.$message.error('删除失败，请检查网络后重试');
        } else {
          this.attachedFiles.splice(index, 1);
          this.emitToParent();
        }
      });
    },
    handleOver(item){
      item.status = 0;
      this.$forceUpdate();
    },
    handleOut(item){
      item.status = 1;
      this.$forceUpdate();
    },
    download(id, event){
      window.open('http://47.104.93.41/api/common/download?id='+id);
    },

    addNewLine(currentIndex, table){

      let lastLine= _.cloneDeep(table[currentIndex]), newLine = {};
      let keys = [
          "dd_products",
          "dd_description",
          "dd_quantity",
          "dd_price",
          "dd_lineAmount"
      ];

  
      keys.forEach(key => {
        newLine[key] = lastLine[key];
      });


      table.splice(currentIndex + 1, 0, newLine);
      this.documentprocess_deliDetail_total_amount = this.computeTableTotal("amount");
      this.documentprocess_deliDetail_total_number = this.computeTableTotal("number");
      this.emitToParent();
    },
    removeCurrentLine(currentIndex, table){
      if (table.length > 1){
        table.splice(currentIndex, 1);
        this.documentprocess_deliDetail_total_amount = this.computeTableTotal("amount");
        this.documentprocess_deliDetail_total_number = this.computeTableTotal("number");
        this.emitToParent();
      }
    },

    /**
     * 商品表格的输入处理
     */
    handleTableInput(scope, key, event){
        let oldData = _.cloneDeep(this.documentprocess_deliDetail[scope.$index]);

        switch(key) {
          case 'dd_price':
            if (/^\d+\.?\d{0,2}$/.test(event.target.value)) {
              oldData[key] =  event.target.value;
              } else {
              oldData[key] =  toFixed(event.target.value);
              }
            oldData.dd_lineAmount = toFixed(oldData.dd_price * oldData.dd_quantity);
            this.documentprocess_deliDetail.splice(scope.$index, 1, oldData);
            this.documentprocess_deliDetail_total_amount = this.computeTableTotal("amount");
            break;
          case 'dd_quantity':
            oldData[key]  =  Number.isNaN(parseInt(event.target.value).toString()) ? '0' : parseInt(event.target.value).toString();
            oldData.dd_lineAmount = toFixed(oldData.dd_price * oldData.dd_quantity);
            this.documentprocess_deliDetail.splice(scope.$index, 1, oldData);
            this.documentprocess_deliDetail_total_amount = this.computeTableTotal("amount");
            this.documentprocess_deliDetail_total_number = this.computeTableTotal("number");
            break;
          
          case 'dd_lineAmount': 
            this.documentprocess_deliDetail_total_amount = this.computeTableTotal("amount");
            break;
        }

        this.emitToParent();
    },

    /**
     * 计算表格的数量总和，金额总和
     * @param {String} type  
     */
    computeTableTotal(type){
      if (type === 'number') {
        let num = 0;
        this.documentprocess_deliDetail.forEach(line => {
          let temp = Number(line.dd_quantity);
          temp = Number.isNaN(temp) ? 0 : temp;
          num += temp;
        });
        return num;
      } else if (type === 'amount'){
        let amount = 0;
        this.documentprocess_deliDetail.forEach(line => {
          let temp = Number(line.dd_lineAmount);
          temp = Number.isNaN(temp) ? 0 : temp;
          amount += temp;
        });
        return toFixed(amount);
      }
    },

    handleSimpleInput(){
      this.emitToParent();
    },

    addContact(type, index){
      if (type == 'log'){
        let keys = [
          "name",
          "tel",
          "email",
          "qq",
          "wechat",
          "factoryName"
        ];
        let lastLine = _.cloneDeep(this.documentprocess_fdn_lcc_dfl_contacts[index]), newLine = {};

        keys.forEach(key => {
          newLine[key] = lastLine[key];
        });

        this.documentprocess_fdn_lcc_dfl_contacts.splice(index + 1, 0, newLine);
        this.emitToParent();
      }
    },
    delContact(type, index){
       if (type == 'log'){
          if (this.documentprocess_fdn_lcc_dfl_contacts.length > 1){
            this.documentprocess_fdn_lcc_dfl_contacts.splice(index, 1);
            this.emitToParent();
          }
       }
    },

    exportMethod() {},

    selFactory(value){
      let currentFactory = this.allSellers.find(e => {
        return e.customerName == this.documentprocess_fdn_fc_factoryName;
      });

      this.documentprocess_fdn_fc_dff_contacts = [{
        name: currentFactory.customerContacts,
        tel: currentFactory.customerPhone,
        email: currentFactory.customerEmail,
        qq: currentFactory.customerQQ || '',
        wechat: currentFactory.customerWechat,
        factoryName: currentFactory.customerName
      }];

      this.documentprocess_fdn_fc_factoryName = currentFactory.customerName;

      this.factoryMesg = {        
        name: currentFactory.customerContacts,
        tel: currentFactory.customerPhone,
        email: currentFactory.customerEmail,
        qq: currentFactory.customerQQ || '',
        wechat: currentFactory.customerWechat
      };
      
      this.emitToParent();
   },

    /**选择币种 */
    currencySel(name){
      return (h, {column, $index}) => {
        let self = this;
        return  h("div", {
          attrs: {
            class: "select-currency"
          }
        }, [
          h("span", name),
          h("select", {domProps: {
            value: self.documentprocess_fdn_currencyValue
          },
          on: {
            change: function(event){
              self.documentprocess_fdn_currencyValue = event.target.value;
              self.emitToParent();
            }
          }
          },[
            h("option", "人民币"),
            h("option", "美元"),
            h("option", "加元"),
            h("option", "欧元"),
          ])
        ]);
      }
    }
  },

  watch: {
    datas(newValue, oldValue){
      this.keys.forEach(key => {
        this[key] = _.cloneDeep(newValue[key]);
      });
      this.factoryMesg = _.cloneDeep(this.datas.documentprocess_fdn_fc_dff_contacts[0]);
      this.hasBind = true;
    }
  },
  data() {
    return {
      id: '',
      formInstId: '',
      attachedFiles: [],

      //绑定的外贸订单id
      bindingFormInstId: '',

      orderCode: '',
      buyerName: '',
      documentprocess_fdn_bindFContracts: [],
      documentprocess_fdn_bindDContracts: [],
      documentprocess_fdn_contracts: '',

      //发货时间
      documentprocess_fdn_time: '',
      //交易方式
      documentprocess_fdn_tradeTerm: '',
      //海关编码
      documentprocess_fdn_hscode: '',
      //other
      documentprocess_fdn_other: '',
      //工厂联系方式
      documentprocess_fdn_fc_factoryName: '',
      documentprocess_fdn_fc_dff_contacts:[ 
        {
            name: '',
            tel: '',
            email: '',
            qq: '',
            wechat: '',
            factoryName: ''
        }
      ],

       //物流联系方式
      documentprocess_fdn_lcc_logisticName: '',
      documentprocess_fdn_lcc_dfl_contacts: [
        {
              name: '',
              tel: '',
              email: '',
              qq: '',
              wechat: ''
        }
      ],

      documentprocess_deliDetail_total_number: '', //数量总和
      documentprocess_deliDetail_total_amount: '', //金额总和

      //发货明细
      documentprocess_deliDetail: [
        {
          dd_products: '',
          dd_description: '',
          dd_quantity: '',
          dd_price: '',
          dd_lineAmount: ''
        }
      ],
      keys: [
        "id",
        "formInstId",
        "attachedFiles",
        "bindingFormInstId",
        "orderCode",
        "buyerName",
        "documentprocess_fdn_bindFContracts",
        "documentprocess_fdn_bindDContracts",
        "documentprocess_fdn_contracts",
        "documentprocess_fdn_currencyValue",
        "documentprocess_fdn_time",
        "documentprocess_fdn_tradeTerm",
        "documentprocess_fdn_hscode",
        "documentprocess_fdn_other",
        "documentprocess_fdn_fc_factoryName",
        "documentprocess_fdn_fc_dff_contacts",
        "documentprocess_fdn_lcc_logisticName",
        "documentprocess_fdn_lcc_dfl_contacts",
        "documentprocess_deliDetail_total_number",
        "documentprocess_deliDetail_total_amount",
        "documentprocess_deliDetail"
      ],
      dialogCtrl: {
        outerVisible: false,
        innerVisible: false,
      },
      page: {
        currPage: 1,
        pageSize: 30,
        totalSize: 0
      },
      loading: false,
      selectOrder:[],
      selectOrder2:[],
      dialogVisible: false, //默认点击发送的弹窗不显示
      canNotSelect: true,
      canNotSelect2: true,
      hasBind: false,
      orderNumber: '',
      foreignTradeContractNumber: '',
      bindFContracts: [],
      bindDContracts: [],
      queryOrderData: [],
      queryOrderData2: [],
      table1Data: [],
      table2Data: [],
      showftc: null,
      showdtcs: [],
      orangeDate: '',
      pickerOrange:{
          shortcuts: [{
            text: '最近一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            }
          }]
        },
      allSellers: [],
      sellOptions: [],
      factoryMesg: {
        name: "",
        tel: "",
        email: "",
        qq: "",
        wechat: ""
      }
    }
  },
  props: {
    datas: {
      type: Object,
      required: true
    },
    editable: {
      type: Boolean,
      required: true
    },
    bus: {
      type: Object,
      required: true
    }
  },
  components: {}
}
</script>

<style  lang="scss">
body {
    .dialog-footer {
        text-align: center;
        button {
            margin-right: 50px;
        }
    }
}

.noticeofdelivery {
    padding: 20px;
    border: 1px solid #999;
    > h2 {
        text-align: center;
    }

  .select-currency {
      select {
        margin-left: 12px;
        height: 30px;
        width: 60px;
      }
    }

    .factory .el-select {
      width: 100%;
    }

    font-size: 15px;

    a {
        color: #409EFF;
      }

      .el-col-offset-4 {
        margin-left: 16.66667% !important;
      }


      .el-input-number__decrease,
      .el-input-number__increase {
        width: 20px;

        border: none !important;
        background: transparent;
      }

      .el-input-number {
          width: 100%;
          min-width: 100px;
      }


      .tcf-table {
        .el-col {
          border: none !important;
          padding-right: 5px;
          border-bottom: 1px solid #999 !important;
          border-right: 1px solid #999 !important;
          margin-left: 0 !important;
        }
      }

    .el-table {
        td {
            border: 1px solid #e6ebf5;
        }
    }

    .head {
      position: relative;

      >h2 {
        text-align: center;
      }


        .select-orders {

            padding: 30px 20px;

            li {
                padding: 5px 0;
            }

            .select-orders-line {
              height: 40px;
              line-height: 40px;
            }

            .el-col {
                border: none !important;
            }
        }

        .el-input__inner {
            border: none;
            outline: none;
            background: transparent;
        }

        .procurement-contract {
            width: 100%;
            height: 40px;
            margin-bottom: 20px;
            text-align: right;
            .procurement-contract-inner {
                width: 50%;
                float: right;
                span {
                    display: inline-block;
                    width: 30%;
                }
                .el-input {
                    width: 65%;
                }
            }

        }
        .factory-contact-mode {
            width: 100%;
            border-top: 1px solid #999;
            border-left: 1px solid #999;
            margin-top: 20px;
            margin-bottom: 20px;
            font-size: 12px;

            input {
              width: 90%;
              height: 90%;
              border: none;
              background-color: transparent;
            }

            .el-input__inner {
                border: none;
                outline: none;
            }

            .el-row {

              transition: all 0.2s linear;
              &:hover {
                background-color: #c5e8ff !important;
              }
            }

            .operation {
              text-align: center;
              color: #409EFF;
              >button {
                padding: 0 2px;
                font-size: 12px;
                cursor: pointer;
              }
            }
        }

        .extra-table, {
          font-size: 14px;
          .extra-money {
            border: 1px solid #e6ebf5;
            border-top: none;
            text-align: center;
            color: #5a5e66;

            .el-col {
              height: 40px;
              line-height: 40px;
              border: none !important;

              &:nth-child(1){
                border:none;
                border-right: 1px solid #e6ebf5 !important;
              }
            }

            input {
              width: 90%;
              height: 36px;
              border: none;
              outline: none;
              text-indent: 1em;
              color: #5a5e66;
            }
          }
        }
        .btns {
            position: absolute;
            top: -6px;
            padding: 0 20px;
            text-align: center;

            .bind {
                float: left;
            }
            .export {
                float: right;
            }
        }

        .tcf-table {
            margin-top: 20px;
            padding: 20px;
            box-sizing: border-box;
            width: 100%;

            .el-table__body-wrapper {
              overflow: hidden;
            }


            .procurement-contract-inner {
              input {
                border: none;
                border: 1px solid #999;
                outline: none;
                border-radius: 2px;
                width: 200px;
                height: 30px;
                background-color: transparent;
              }
            }

            .cell {
              height: 100%;
              input {
                border: none;
                outline: none;
                background-color: transparent;
                width: 90%;
                height: 100%;
              }
            }

            h2 {
                text-align: center;
                padding: 10px 0;
            }

            .tcf-table-title {
                text-align: center;
            }

            .el-col {
                height: 50px;
                line-height: 50px;
                border: 1px solid #999;
                margin-left: -1px;
                margin-top: -1px;
                padding-left: 5px;
            }

            .no-border {
                //   border: none !important;
            }

            .special-row {
                .el-col {
                    height: 25px;
                    line-height: 25px;
                }
            }
        }

        .upload {
            > div {
                border: 1px solid #999;
                padding: 20px 0 40px 20px;
            }

            .upload-btn {
                position: relative;
                > input {
                    opacity: 0;
                    width: 100px;
                    height: 40px;
                    position: absolute;
                    top: 0;
                    left: 0;
                }
            }

            .upload-files {

                > li {
                    width: 300px;
                    padding: 10px 0;
                    transition: all 0.5s linear;

                    &:hover {

                      >span {
                        color: #409EFF;
                      }
                    }
                  }

                font-size: 16px;
                span {
                    padding: 0 10px;
                    cursor: pointer;
                    display: inline;
                }
                span.el-icon-close:hover {
                    cursor: pointer;
                }
            }
            .upload-hint {
                font-size: 20px;
                margin-bottom: 10px;
            }
        }
    }

    .bind-window {
        .el-form--inline .el-form-item {
            margin-right: 15px;
        }

        td {
            border: 1px solid #e6ebf5;
        }

        td:not(.el-table_1_column_1) {
            width: 120px;
            min-width: 120px;
        }

        .dialog-footer {
            text-align: center;
            button {
                margin-right: 80px;
            }
        }

        a {
            color: #409EFF;
        }

    }
}
</style>
